<template>
 <van-button
      class="follow-btn"
      type="info"
      color="#3296fa"
      round
      size="small"
      icon="plus"
      :loading="followLoading"
      v-if="!isFollowed"
      @click="onFollow"
    >关注</van-button>
 <van-button
      class="follow-btn"
      round
      size="small"
      v-else
      :loading="followLoading"
      @click="onFollow"
    >已关注</van-button>
</template>

<script>
import { addFollowAPI, deleteFollowAPI } from '../../../api/index.js'
export default {
  name: 'FollowUser',
  // model: {
  //   prop: 'isFollowed', // 表示的是修改value名称的值
  //   event: 'changeIsFollowed' // 表示的是修改input名称的值
  // },
  props: {
    isFollowed: {
      type: Boolean,
      default: false
    },
    userId: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      followLoading: false // 关注按钮加载状态
    }
  },
  methods: {
    // 关注，取消关注用户
    async onFollow () {
      let message = '操作成功'
      try {
        // 调用接口前开启加载
        this.followLoading = true
        if (this.isFollowed) {
          // 已关注，需要取关
          await deleteFollowAPI(this.userId)
          message = '取关成功'
        } else {
          // 未关注，需要关注
          await addFollowAPI({
            target: this.userId
          })
          message = '关注成功'
        }
        // this.$emit('changeIsFollowed', !this.isFollowed)
        this.$emit('update:isFollowed', !this.isFollowed)
        this.$toast.success(message)
      } catch (error) {
        console.log(error)
        // 当后端返回错误代码为400时，表面不可以关注自己
        if (error.response && error.response.status === 400) {
          message = '你不能关注你自己'
        } else {
          message = '网络异常，请稍后重试'
        }
        this.$toast.fail(message)
      }

      // 无论成功还是失败都需要关闭加载状态
      this.followLoading = false
    }
  }
}
</script>

<style>

</style>
